package com.SmartCare.utils;

import org.springframework.stereotype.Service;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;


@Service
public class ImgCompressUtil {


    /**
     * 压缩图片并返回压缩后的字节数组
     *
     * @param imageBytes 原始图片字节数组
     * @param formatName 图片格式
     * @param maxSize    最大尺寸（单位：KB）
     * @return 压缩后的字节数组
     * @throws IOException 压缩过程中可能出现的IO异常
     */
    public byte[] compressImage(byte[] imageBytes, String formatName, int maxSize) throws IOException {
        BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        // 获取原始图像的宽度和高度
        int originalWidth = image.getWidth();
        int originalHeight = image.getHeight();
        // 计算压缩比例
        double scaleFactor = Math.sqrt((double) maxSize / (originalWidth * originalHeight));

        // 压缩图片
        int newWidth = (int) (originalWidth * scaleFactor);
        int newHeight = (int) (originalHeight * scaleFactor);
        Image scaledImage = image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);

        BufferedImage bufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bufferedImage.createGraphics();
        g2d.drawImage(scaledImage, 0, 0, null);
        g2d.dispose();

        // 将压缩后的图片写入输出流
        ImageIO.write(bufferedImage, formatName, outputStream);

        return outputStream.toByteArray();

    }
}
